package com.restkeeper.controller.store;

import com.restkeeper.entity.Dictionary;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.response.page.PageVO;
import com.restkeeper.service.ISysDictService;
import com.restkeeper.store.entity.Dish;
import com.restkeeper.store.entity.DishFlavor;
import com.restkeeper.store.entity.Remark;
import com.restkeeper.store.service.IDishService;
import com.restkeeper.utils.SystemCode;
import com.restkeeper.vo.store.DishFlavorVO;
import com.restkeeper.vo.store.DishVO;
import com.restkeeper.vo.store.SaleStatusVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Api(tags = { "菜品管理" })
@RestController
@RequestMapping("/dish")
public class DishController{
    @Reference(version = "1.0.0", check=false)
    private IDishService dishService;
    @Reference(version = "1.0.0", check=false)
    private ISysDictService dictService;


    @ApiOperation(value = "默认分类")
    @GetMapping("/flavorList")
    public List<DishFlavorVO>  flavorList(){
        List<Dictionary>  list= dictService.getDictionaryList(SystemCode.DICTIONARY_FLAVOR);
        List<DishFlavorVO>  dishFlavorsVOList = new ArrayList<>();
        list.forEach(d->{
            DishFlavorVO dishFlavorVO = new DishFlavorVO();
            dishFlavorVO.setFlavor(d.getDictName());
            String flavorValue =d.getDictData();
            String quflavorValue=flavorValue.substring(flavorValue.indexOf("[")+1,flavorValue.indexOf("]"));
            if(StringUtils.isNotEmpty(quflavorValue)){
                String[] flavor_array= quflavorValue.split(",");
                dishFlavorVO.setFlavorData(Arrays.asList(flavor_array));
            }
            dishFlavorsVOList.add(dishFlavorVO);
        });
        return dishFlavorsVOList;
    }

    @ApiOperation(value = "添加菜品")
    @PostMapping("/add")
    public boolean add(@RequestBody DishVO dishVO){
        //设置菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishVO, dish);
        //设置口味
        List<DishFlavorVO>  dishFlavorsVO = dishVO.getDishFlavors();
        List<DishFlavor> flavorList =new ArrayList<DishFlavor>();
        for (DishFlavorVO dishFlavorVO : dishFlavorsVO) {
            DishFlavor dishFlavor = new DishFlavor();
            dishFlavor.setFlavorName(dishFlavorVO.getFlavor());
            dishFlavor.setFlavorValue(dishFlavorVO.getFlavorData().toString());
            flavorList.add(dishFlavor);
        }
        return dishService.save(dish,flavorList);
    }

    @ApiOperation(value = "根据名称分页")
    @GetMapping("/pageList/{page}/{pageSize}")
    public PageVO<Dish> queryPageByName(@PathVariable long page, @PathVariable long pageSize, @RequestParam(value = "name", required = false) String name) {
        return new PageVO<>(dishService.queryByName(name, page, pageSize));
    }

//    @GetMapping("/queryByName/{code}/{page}/{pageSize}")
//    public PageVO<Dish> searchByCode(@PathVariable String code,@PathVariable int page,@PathVariable int pageSize) throws Exception {
//        SearchResult<DishEs> searchResult = dishSearchService.searchDishByCode(code,page,pageSize);
//        PageVO<Dish> pageResult = new PageVO<>();
//        pageResult.setItems(searchResult
//                            .getRecords()
//                            .stream()
//                            .map(d->{
//                                Dish dish = new Dish();
//                                dish.setDishId(d.getId());
//                                dish.setDishName(d.getDish_name());
//                                dish.setPrice(d.getPrice());
//                                d.setCode(d.getCode());
//                                return dish;
//                            })
//                            .collect(Collectors.toList()));
//        pageResult.setCounts(searchResult.getTotal());
//        pageResult.setPage(page);
//        pageResult.setPagesize(pageSize);
//        long pageCount =searchResult.getTotal()%pageSize==0?searchResult.getTotal()/pageSize:searchResult.getTotal()/pageSize+1;
//        pageResult.setPages(pageCount);
//
//        return pageResult;
//    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id获取菜品信息")
    public DishVO getDish(@PathVariable String id){
        Dish dish = dishService.getById(id);
        if(dish==null){
            throw new BussinessException("菜品不存在");
        }
        DishVO dishVo =new DishVO();
        BeanUtils.copyProperties(dish, dishVo);
        //口味列表
        List<DishFlavorVO> dishFlavorVOList=new ArrayList<>();
        List<DishFlavor> dishFlavorList = dish.getFlavorList();
        for (DishFlavor flavor : dishFlavorList) {
            DishFlavorVO dishFlavorVO= new DishFlavorVO();
            dishFlavorVO.setFlavor(flavor.getFlavorName());
            String flavorValue = flavor.getFlavorValue();
            String quflavorValue=flavorValue.substring(flavorValue.indexOf("[")+1,flavorValue.indexOf("]"));
            if(StringUtils.isNotEmpty(quflavorValue)){
               String[] flavor_array= quflavorValue.split(",");
               dishFlavorVO.setFlavorData(Arrays.asList(flavor_array));
            }
            dishFlavorVOList.add(dishFlavorVO);
        }
        dishVo.setDishFlavors(dishFlavorVOList);
        return  dishVo;
    }

    @ApiOperation(value = "修改")
    @PutMapping("/update")
    public boolean update(@RequestBody DishVO dishVO){
        Dish dish = dishService.getById(dishVO.getId());
        BeanUtils.copyProperties(dishVO, dish);
        //设置口味
        List<DishFlavorVO>  dishFlavorsVO = dishVO.getDishFlavors();
        List<DishFlavor> flavorList =new ArrayList<DishFlavor>();
        for (DishFlavorVO dishFlavorVO : dishFlavorsVO) {
            DishFlavor dishFlavor = new DishFlavor();
            dishFlavor.setFlavorName(dishFlavorVO.getFlavor());
            dishFlavor.setFlavorValue(dishFlavorVO.getFlavorData().toString());
            flavorList.add(dishFlavor);
        }
        return dishService.update(dish,flavorList);
    }

//   @GetMapping("/addFlavor/{flavorName}/{flavorValue}")
//    @ApiOperation(value = "添加口味")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "path", name = "flavorName", value = "口味名称", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "path", name = "flavorValue", value = "口味标签", required = true, dataType = "String")})
//    public boolean addFlavor(@PathVariable String flavorName,@PathVariable String flavorValue){
//        Dictionary dictionary = new Dictionary();
//        dictionary.setCategory("flavor");
//        dictionary.setDictName(flavorName);
//        dictionary.setDictData(flavorValue);
//
//        return dictService.save(dictionary);
//    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @ApiOperation(value = "删除")
    @DeleteMapping("/delete")
    public boolean delete(@RequestBody List<String> ids){
        return dishService.deleteDishs(ids);
    }


    /**
     * 设置菜品售卖状态
     * @param saleStateVO
     * status; // 0 停售 1 启售
     * @return
     */
    @ApiOperation(value = "设置菜品售卖状态")
    @PutMapping("/updateStatus")
    public boolean updateSaleStatus(@RequestBody SaleStatusVO saleStateVO){
        if(SystemCode.FORBIDDEN==saleStateVO.getStatus()){
           return dishService.forbiddenSalesStatus(saleStateVO.getIds());
        }else if(SystemCode.ENABLED==saleStateVO.getStatus()){
            return dishService.enabledSalesStatus(saleStateVO.getIds());
        }
        return false;
    }

    @ApiOperation(value = "查询可用的菜品列表")
    @GetMapping("/findEnableDishList/{categoryId}")
    public List<Map<String,Object>> findEnableDishList(@PathVariable String categoryId,
                                                       @RequestParam(value = "name",defaultValue = "") String name){
        return dishService.findEnableDishListInfo(categoryId, name);
    }

}